<template>
	<view>
		<view class="title">
			<p class="title-c">{{count}}′</p>
			<p class='title-p'>{{$t('connectNet.qr_code_distance_warning')}}</p>
		</view>
		<view class="qrcode" v-show="showQrImg" :style="{'height':canvasrpx+50+'px'}">
			<canvas class="qrcanvas" v-if="!cpbarCanvasImg" :style="{'width':canvasrpx+'px','height':canvasrpx+'px'}"
				canvas-id="qrcode" style="margin: 40rpx auto;" />
			<image class="qrimg" :style="{'width':canvasrpx+'px','height':canvasrpx+'px'}" style="margin: 40rpx auto;"
				v-if="cpbarCanvasImg && qrsize == 1" :src="cpbarCanvasImg" mode="" />
			<image class="qrimg2" style="margin: 40rpx auto;" v-if="cpbarCanvasImg && qrsize == 2" :src="cpbarCanvasImg"
				mode="" />
		</view>
		<view class="qrcode-hint">
			<span>{{$t('connectNet.scan_qr_code_device')}}</span>{{$t('connectNet.scan_qr_code_supported')}}。
		</view>
		<view class="foot-button">
			<button class="block radius-btn" @tap="nextstep()" type="operation">{{$t('JLink.publicText.cancel')}}</button>
		</view>
		<uni-popup ref="connectPopup">
			<view class="popup-connect" style="width: 600rpx;">
				<view class="popup-header">
					<text class="p-title">{{$t('connectNet.device_connection_issues')}}</text>
					<uni-icons class="close" type="closeempty" color="#AFAFAF" @click="closecode()"></uni-icons>
				</view>
				<view class="u-f-c popup-content">
					<text>1、{{$t('connectNet.ensure_power_data_cable')}};</text>
					<text>2、{{$t('connectNet.first_setup_network_range')}};</text>
					<text>3、{{$t('connectNet.observe_device_indicator')}};</text>
					<text>4、{{$t('connectNet.if_no_indication')}}</text>
					<text style="color: #FF0025;">{{$t('connectNet.panoramic_light_bulb_warning')}}</text>
				</view>
				<view class="popup-button">
					<button @tap="closecode()" class="block radius-btn" type="primary">{{$t('connectNet.got_it')}}</button>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="devicePopup" :is-mask-click="false">
			<view class="devicePopup-connect">
				<!-- <view class="popup-qrimg" :style="{'width':canvasrpx+'px','height':canvasrpx+'px'}"> -->
				<view class="popup-qrimg" :style="{'height':canvasrpx+40+'px'}">
					<image class="qrimg" :style="{'width':canvasrpx-20+'px','height':canvasrpx-20+'px'}"
						v-if="cpbarCanvasImg && qrsize == 1" :src="cpbarCanvasImg" mode="aspectFit" />
					<image class="qrimg2" v-if="cpbarCanvasImg && qrsize == 2" :src="cpbarCanvasImg" mode="aspectFit" />
				</view>
				<view class="popup-device">
					<view class="title-number">
						<text>发现待添加设备：{{list.length}}个</text>
						<uni-icons type="closeempty" @click="closeDevicePopup()" size="24"></uni-icons>
					</view>
					<view class="device-list" @click="selectDevice(list[0])" v-if="list.length == 1">
						<view class="deviceImg">
							<image class="qrimg" :src="list[0].deviceInfo.devicePic" mode="">
							</image>
						</view>
						<view class="device-info">
							<view class="">
								{{list[0].deviceInfo.deviceTypeName?list[0].deviceInfo.deviceTypeName:''}}
							</view>
							<view class="text1">
								点击添加
							</view>
						</view>
					</view>
					<view class="device-list device-lists" v-if="list.length > 1">
						<view @click="selectDevice(item,index)" class="deviceImg" v-for="(item,index) in list"
							:key="index">
							<image class="qrimg" style="" :src="item.deviceInfo.devicePic" mode="">
							</image>
						</view>
					</view>
				</view>
				<!-- <view class="popup-device" v-if="list.length > 1">
					<view class="title-number">
						<text>发现待添加设备：{{list.length}}个</text>
						<uni-icons type="closeempty" size="24"></uni-icons>
					</view>
					<view class="device-list device-lists">
						<view @click="selectDevice(item,index)" class="deviceImg" v-for="(item,index) in list"
							:key="index">
							<image class="qrimg" style="" :src="item.deviceInfo.devicePic" mode="">
							</image>
						</view>
					</view>
				</view> -->
			</view>
		</uni-popup>
		<j-show-toast :show="jshowtoast" :title="title">
		</j-show-toast>
	</view>
</template>

<script>
	const {
		hexStringToArrayBuffer,
		ab2hex,
		hexToString,
	} = require('@/utils/util.js');
	const { stringToUTF8Bytes,useStrFill,stringToByte,strToHexCharCode } = require('@/jvss/pagesDevice/utils/index.js');
	import {
		buletoothCodeMsg
	} from '@/utils/errorCode.js'
	// import QRCode from './common/weapp-qrcode.js';
	import uQRCode from './common/uqrcode.js' //引入uqrcode.js
	export default {
		data() {
			return {
				count: 180, //倒计时
				Randnum: '', //随机数
				ipnum: '', //ip地址
				timer: null,
				sizetimer: null,
				req: null,
				WIFI: {}, //WiFi信息
				qrShow: false,
				cpbarCanvasImg: '',
				ScreenBrightness: '',
				adminToken: '',
				qrsize: 1,
				// 蓝牙配网
				// 设备列表
				list: [],
				isStop: false,
				serviceId: '00001910-0000-1000-8000-00805f9b34fb',
				characteristicId: '00002b10-0000-1000-8000-00805f9b34fb',
				isLinked: false, //连接蓝牙
				isReceived: false, //设备收到消息
				isDistributeNet: false, //配网
				time: 180,
				timerId: null,
				canvasrpx: 0,
				isopenBlueState: 0, //蓝牙会出现第一次初始化失败,1代表重新调用一次
				title: '',
				jshowtoast: false,
				blueError: false, //第一次蓝牙连接失败判断
				isnum: 0,
				showQrImg:true,
				audioCode:null,
                version: 'v1',
                buffer: '',
                maxMTU: 512,
			}
		},
		onLoad(opt) {
			let rpx;
			//获取屏幕宽度，获取自适应单位
			wx.getSystemInfo({
				success: (res)=> {
					let screenWidth = res.screenWidth;
					let screenHeight = res.screenHeight;
					console.log(res,'获取设备信息',screenWidth)
					if(screenWidth > 480){
						console.log('ipad????')
						rpx = res.windowWidth - 280
					}else{
						rpx = res.windowWidth - 40
					}
				},
			})
			uni.setNavigationBarTitle({
				title: this.$t('connectNet.network_process')
			});
			this.canvasrpx = rpx;
			// console.log(this.canvasrpx)
			console.log(opt.device)
			this.WIFI = JSON.parse(opt.device);
			// wx.getScreenBrightness({
			// 	success: res => {
			// 		this.ScreenBrightness = res.value
			// 	}
			// })
			// wx.setScreenBrightness({
			// 	value: 1, //屏幕亮度值，范围 0~1，0 最暗，1 最亮
			// })
			// this.$refs.devicePopup.open();
			// this.createAudio()
		},
		onReady() {
			this.randomnumber();
			this.ip();
			setTimeout(() => {
				// this.openBluetoothAdapter();
			}, 1050)
		},
		onUnload() {
			this.onClear()
			// //设置屏幕亮度为原来亮度
			// wx.setScreenBrightness({
			// 	value: this.ScreenBrightness
			// })
			// // 停止搜索蓝牙设备
			// this.stopBluetoothDevicesDiscovery();
			// // 断开蓝牙模块
			// this.closeBluetoothAdapter()
		},
		onHide() {
			// wx.setScreenBrightness({
			// 	value: this.ScreenBrightness
			// })
			// this.onClear();
		},
		methods: {
			//添加音频
			createAudio(){
				this.audioCode = wx.createAudioContext('qrcodeAudio')
				this.audioCode = wx.createInnerAudioContext({useWebAudioImplement: true})
				this.audioCode.src = 'https://statics.xmcsrv.net/weixin/paireVoice.mp3'
				this.audioCode.autoplay = false
				this.audioCode.loop = false
			},
			// 清楚循环定时器
			onClear() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
				if (this.sizetimer) {
					clearInterval(this.sizetimer);
					this.sizetimer = null
				}
			},
			closeDevicePopup() {
				this.$refs.devicePopup.close();
				this.showQrImg = true
				this.stopBluetoothDevicesDiscovery();
				if (this.timerId) {
					clearInterval(this.timerId);
					this.timerId = null
				}
			},
			// 随机十位数
			randomnumber() {
				let code = '';
				const codeLength = 10;
				const random = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd'];
				for (let i = 0; i < codeLength; i++) {
					let index = Math.floor(Math.random() *
						14);
					code += random[index];
				}
				this.Randnum = code;
			},
			// 获取ip地址
			ip() {
				// wx.getLocalIPAddress({
				// 	success: res => {
				// 		const index = res.localip.lastIndexOf(".")
				// 		this.ipnum = res.localip.substring(index + 1, res.localip.length)
				// 		console.log(this.ipnum, 'ip地址')
				// 		this.couponQrCode();
				// 	}
				// })
				this.couponQrCode();
			},
			// 生成二维码
			async couponQrCode() {
				let url =
					`S:${this.WIFI.wifiName}
P:${this.WIFI.wifiPwd}
E:1
M:020000000000
I:0
B:${this.Randnum}
`
				this.qrShow = true;
				uni.showLoading({
					mask: true,
					title: this.$t('connectNet.qr_code_generating')
				})
				// await new QRCode('qrcode', {
				// 	text: url,
				// 	width: this.canvasrpx,
				// 	height: this.canvasrpx,
				// 	// showLoading: true, // 是否显示loading
				// 	// loadingText: '二维码生成中', // loading文字
				// 	colorDark: "#000",
				// 	colorLight: "#FFFFFF",
				// 	correctLevel: QRCode.CorrectLevel.L,
				// 	callback: (res) => {
				// 		uni.hideLoading()
				// 		this.$logs({
				// 			info: '生成二维码',
				// 			data: res
				// 		})
				// 		console.log("生成二维码", res)
				// 		this.cpbarCanvasImg = res.path
				// 		this.audioCode.play()
				// 	}
				// })
				await uQRCode.make({
					canvasId: 'qrcode',
					componentInstance: this,
					text: url,
					size: this.canvasrpx,
					margin: 0,
					backgroundColor: '#ffffff',
					foregroundColor: '#000000',
					fileType: 'jpg',
					errorCorrectLevel: uQRCode.errorCorrectLevel.L,
					success: (res) => {
						// console.log(res,'生成二维码')
						uni.hideLoading()
						this.$logs({
							info: '生成二维码',
							data: res
						})
						this.cpbarCanvasImg = res
						// this.audioCode.play()
					}
				})
				this.verification();
				this.timer = setInterval(() => {
					setTimeout(() => {
						this.polling();
					}, 0)
				}, 3500)
				this.sizetimer = setInterval(() => {
					this.switchingSize();
				}, 1000)
			},
			switchingSize() {
				if (this.qrsize == 1) {
					this.qrsize = 2;
				} else {
					this.qrsize = 1;
				}
			},
			// 倒计时
			verification() {
				var times = setInterval(() => {
					this.count--;
					if (this.count <= 0) {
						this.$refs.devicePopup.close();
						clearInterval(times);
						this.onClear();
						setTimeout(() => {
							this.$refs.connectPopup.open();
						}, 500)
					}
				}, 1000);
			},
			// 轮询设备连接状态
			polling() {
				// 时间戳 	
				let time = parseInt(new Date().getTime() / 1000) + '';
				let url = 'https://pairing.xmcsrv.net/api/query?B=' + this.Randnum + '&T=' +
					time
				this.req = uni.request({
					url: 'https://pairing.xmcsrv.net/api/query?B=' + this.Randnum + '&T=' +
						time,
					// url: 'http://122.9.134.27:8031/api/query?B=' + this.Randnum + '&T=' +time,
					method: 'GET',
					header: {
						'content-type': 'application/json;charset:utf-8'
					},
					success: (res) => {
						// console.log(res);
						// #ifdef MP-WEIXIN
						this.$logs({
							info: '二维码配网',
							apiUrl: url,
							data: res
						})
						// this.$logs.apply(getApp().globalData.logger, arguments);
						// #endif
						if (res.data.ret === 200) {
							this.$postPointData({code:'601401', eventName:'start_qrcode_config'})
							console.log('成功', res);
							this.cancelrequest();
							clearInterval(this.timer);
							clearInterval(this.sizetimer);
							let data = {
								pid: res.data.pid,
								deviceNo: res.data.serialNumber,
								// deviceType:res.data.deviceType,
								adminToken: res.data.adminToken || ''
							}
							if (res.data.deviceType) {
								data.deviceType = res.data.deviceType
							}
							this.$postPointData({code:'601402', eventName:'qrcode_config_success'})
							this.$logs({
								info: '二维码配网成功获取数据',
								data: data,
								localAdmin: this.adminToken
							})
							console.log('this.adminToken==', this.adminToken, 'res.data.adminToken==', res.data
								.adminToken);
							if (res.data.adminToken) {
								// if((this.adminToken!=res.data.adminToken)){
								// 	this.adminToken = res.data.adminToken
								// 	this.getToken(res.data.serialNumber,res.data.pid,data)
								// }
								let url =
									`/jvss/pagesDevice/device/bluetooth/equipment-rename?device=${encodeURIComponent(JSON.stringify(data))}&connecttype=qrcode`
								uni.reLaunch({
									url: url
								});
							} else {
								// this.cancelrequest();
								// clearInterval(this.timer);
								uni.reLaunch({
									url: './setpassword?device=' + encodeURIComponent(JSON.stringify(
										data))
								});
							}
						}
					}
				})
			},
			cancelrequest() {
				this.req.abort();
			},
			nextstep() {
				uni.showModal({
					title: this.$t('JLink.prompt.title'),
					content: this.$t('connectNet.interrupt_setup_confirm'),
					success: (res)=> {
						if (res.confirm) {
							this.onClear()
							uni.navigateBack({
								delta: 1, //返回层数，2则上上页
							})
						}
					}
				});
				this.$refs.connectPopup.close();
			},
			closecode() {
				uni.navigateBack({
					delta: 1,
				})
			},

			// 蓝牙配网
			// 初始化蓝牙
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: e => {
						console.log('初始化蓝牙成功:' + e);
						// console.log(JSON.stringify(e));
						this.getBluetoothAdapterState();
						this.startBluetoothDevicesDiscovery()
					},
					fail: e => {
						// console.log(e)
						// if (this.isopenBlueState == 0) {
						// 	setTimeout(() => {
						// 		this.isopenBlueState == 1
						// 		this.openBluetoothAdapter();
						// 	}, 100)
						// }
						console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
						if (e.errCode !== 0) {
							// initTypes(e.errCode, e.errMsg);
						}
					}
				});
			},
			// 开始搜索蓝牙设备
			startBluetoothDevicesDiscovery() {
				uni.startBluetoothDevicesDiscovery({
					// services: ['A201'],
					success: e => {
						console.log('开始搜索蓝牙设备:' + JSON.stringify(e));
						this.onBluetoothDeviceFound();
					},
					fail: e => {
						uni.showToast({
							title: e.errCode
						})
						// console.log('搜索蓝牙设备失败：' + JSON.stringify(e));
						// console.log('搜索蓝牙设备失败，错误码：' + e.errCode);
						if (e.errCode != 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},
			// 停止搜索蓝牙设备
			stopBluetoothDevicesDiscovery(types) {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('二维码停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('二维码停止搜索蓝牙设备失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},
			// 断开蓝牙模块
			closeBluetoothAdapter(OBJECT) {
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('二维码断开蓝牙模块成功');
					}
				});
			},
			// 获取本机蓝牙适配器状态
			getBluetoothAdapterState() {
				uni.getBluetoothAdapterState({
					success: res => {
						console.log('获取本机蓝牙适配器状态成功', res);
					},
					fail: e => {
						console.log('获取本机蓝牙适配器状态失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},
			// 发现外围设备
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound(devices => {
					// console.log('开始监听寻找到新设备的事件', devices);
					this.getBluetoothDevices();
				});
			},
			// 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						// console.log('蓝牙设备list', JSON.stringify(res));
						this.list = []
						res.devices.forEach((item, index) => {
							if (ab2hex(item.advertisData).endsWith('8b8b8b8b')|| ab2hex(item.advertisData).startsWith('8b8b')) {
								// console.log(item, '蓝牙监测到的设备')
                                let advertisDataStr = ab2hex(item.advertisData)
								this.list.push(item);
								for (let key in item.serviceData) {
									this.$set(item, 'pid', hexToString(ab2hex(item.serviceData[key])))
                                    this.$set(item, 'advertisDataStr', advertisDataStr)
									//根据Pid获取设备信息
									getApp().globalData.api.getDeviceInfoByPID({
										pid: hexToString(ab2hex(item.serviceData[key]))
									}, (result) => {
										this.$set(item, 'deviceInfo', result)
									});
								}
							}
						})
						if (this.list.length !== 0) {
							setTimeout(() => {
								this.$refs.devicePopup.open();
								this.showQrImg = false
								this.stopBluetoothDevicesDiscovery()
							}, 200)
						}
					},
					fail: e => {
						// console.log('获取蓝牙设备错误，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},
			// 选中的设备
			selectDevice(e, index) {
				console.log(e, index);
				this.device = e
                if (this.device.advertisDataStr&&(this.device.advertisDataStr.endsWith('03') || this.device.advertisDataStr.endsWith('02'))) {
                    this.version = 'v2'
                }
				this.createBLEConnection()
			},
			// 连接低功耗蓝牙
			createBLEConnection() {
				let deviceId = this.device.deviceId;
				console.log(deviceId, '连接蓝牙需要的deviceId')
				uni.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					success: res => {
						this.$refs.devicePopup.close();
						this.showQrImg = true
						// 连接设备后断开搜索 并且不能搜索设备
						// uni.showToast({
						// 	title: '连接蓝牙设备成功！',
						// 	icon: "none",
						// 	duration: 2000
						// });
						this.showToast('设备蓝牙连接成功')
						this.isLinked = true
						this.stopBluetoothDevicesDiscovery()
                        if (this.version == 'v1') {
                            this.setBLEMTU()
                        }
						this.getBLEDeviceServices();
						this.$postPointData({code:'601100', eventName:'blue_sys_add_dev_success'})
						this.$logs({
							info: '二维码蓝牙配网连接成功！',
							deviceId: this.device.deviceId,
							res: res
						})
						this.isnum = 0
					},
					fail: e => {
						if (e.errCode == 10003) {
							this.isnum++
							this.$logs({
								info: '二维码蓝牙配网失败后连接次数',
								isnum: this.isnum,
							})
							if (!this.blueError) {
								this.$logs({
									info: '二维码蓝牙配网连接蓝牙第一次失败！',
									deviceId: this.device.deviceId,
									error: e
								})
								setTimeout(()=>{
									this.createBLEConnection();
									this.$logs({
										info: '二维码蓝牙配网延时0.5s连接第二次',
										deviceId: this.device.deviceId,
										error: e
									})
								},500)
								this.blueError = true;
								// uni.showToast({
								// 	title: '连接蓝牙第一次失败！',
								// 	duration: 2000
								// })
								return;
							}
							if (this.blueError) {
								uni.showToast({
									title: '连接蓝牙失败,请重新尝试',
									icon: 'error',
									duration: 2000
								})
								this.blueError = false;
								this.$logs({
									info: '二维码蓝牙配网连接蓝牙第二次失败！',
									deviceId: this.device.deviceId,
									error: e
								})
							}
						}
						this.$logs({
							info: '二维码蓝牙配网连接蓝牙失败！',
							deviceId: this.device.deviceId,
							device: this.device,
							error: e
						})
						console.log('连接低功耗蓝牙失败，错误码：' + e.errCode);
					}
				});
			},
			// 设置蓝牙低功耗的最大传输单元
			setBLEMTU(num, callback) {
				let deviceId = this.device.deviceId;
				let mtu = num || 512;
				uni.setBLEMTU({
					deviceId,
					mtu,
					success: (res) => {
						this.$logs({
							info: 'setBLEMTU成功！',
							deviceId: this.device.deviceId,
							device: this.device,
						})
                        if(typeof callback == 'function') {
                            callback()
                        }
						console.log('setBLEMTU成功:' + JSON.stringify(res));
					}
				})
			},
            // 获取初始化信息
            writeBlueDataInit() {
                // let str = this.combineFlame()
                // let flameContent = ''
                let stringBuilder = '8B8B02010009000000'
                // // let wifiNameSizeFill = useStrFill(wifiNameSize.toString(16),2,'0',true)
                // // let wifiPwdSizeFill = useStrFill(wifiPwdSize.toString(16),2,'0',true)
                // // let pwdTypeFill = useStrFill(pwdType.toString(16),2,'0',true)
                // // let wifiPwdStr = strToHexCharCode(wifiPwd)
                // flameContent = `${wifiNameSizeFill}${wifiNameStr}${wifiPwdSizeFill}${wifiPwdStr}${pwdTypeFill}`
                // let flameContentFill = useStrFill(((flameContent.length)/2).toString(16),4,'0',true)
                // stringBuilder =`${stringBuilder}${flameContentFill}${flameContent}`
                let checkCode = this.createCheckCode(stringBuilder)
                stringBuilder = `${stringBuilder}${checkCode}`
                // console.log('wifi===',wifiName,wifiNameStr,wifiNameSize,wifiNameSizeFill,wifiPwdSizeFill);
                // console.log('wifiPwd===',wifiPwd,wifiPwdStr,wifiPwdSize,wifiPwdSizeFill,pwdTypeFill);
                // console.log('1111===',flameContent,flameContent.length,flameContentFill,stringBuilder,checkCode);
                console.log('stringBuilder', stringBuilder.toUpperCase());

                let str = stringBuilder.toUpperCase()
                this.writeBluetoothData(str)
                this.$logs({
                    info: '向蓝牙设备写数据v2',
                    data: str
                })
            },
            writeBluetoothData(str) {
                let deviceId = this.device.deviceId;
                let serviceId = this.serviceId;
                let characteristicId = this.characteristicId;
                uni.writeBLECharacteristicValue({
                    deviceId,
                    serviceId,
                    characteristicId,
                    // 这里的value是ArrayBuffer类型
                    value: hexStringToArrayBuffer(str),
                    writeType: 'write',
                    success: (res) => {
                        this.isReceived = true
                        // uni.showLoading({title:'连接中' })
                    },
                    fail: (err) => {
                        console.log('write err', JSON.stringify(err));
                    }
                })
            },
			// 获取所有服务
			getBLEDeviceServices() {
				let deviceId = this.device.deviceId;
				uni.getBLEDeviceServices({
					deviceId,
					success: res => {
						this.serviceId = res.services[0].uuid
						this.getBLEDeviceCharacteristics()
					},
					fail: e => {
						this.$logs({
							info: '获取设备服务失败，错误码：' + e.errCode,
							deviceId: this.device.deviceId,
							device: this.device,
							error: e
						})
						console.log('获取设备服务失败，错误码：' + e.errCode);
					}
				});
			},
			// 获取某个服务下的所有特征值
			getBLEDeviceCharacteristics() {
				// uni.showLoading({
				// 	mask: true,
				// })
				let deviceId = this.device.deviceId;
				let serviceId = this.serviceId;
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: res => {
						// uni.hideLoading()
						console.log('获取特征', JSON.stringify(res));
						for (var i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i]
							//订阅notify
							if (item.properties.notify || item.properties.indicate) {
								this.notifyBLECharacteristicValue(deviceId, serviceId, item.uuid)
							}
							//写数据
							if (item.properties.write) {
								this.characteristicId = item.uuid
                                if (this.version == 'v1') {
                                    this.writeBlueData()
                                } else if (this.version == 'v2') {
                                    setTimeout(() => {
                                        this.writeBlueDataInit()
                                    }, 200)
                                }
							}
						}
					},
					fail: e => {
						uni.hideLoading()
						this.$logs({
							info: '获取特征值失败，错误码：' + e.errCode,
							deviceId: this.device.deviceId,
							device: this.device
						})
						console.log('获取特征值失败，错误码：' + e.errCode);
					}
				});
			},
			//订阅notify
			notifyBLECharacteristicValue(deviceId, serviceId, characteristicId) {
				// uni.showLoading({
				// 	title: '连接中...',
				// 	mask: true,
				// })
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId,
					serviceId,
					characteristicId,
					success: (res) => {
						// uni.hideLoading()
						console.log('notifyBLECharacteristicValueChange success', res)
						this.onBLECharacteristicValue()
					}
				})
			},
			//向蓝牙写数据
			writeBlueData() {
				this.$postPointData({code:'601101', eventName:'start_blue_config'})
                // 向蓝牙设备发送数据
                let str = this.combineFlame()
                if (this.version == 'v2') {
                    let splice = Math.ceil(str.length / this.maxMTU)
                    for (var i = 0; i < splice; i++) {
                        let data = str.substring(i * this.maxMTU, this.maxMTU + i * this.maxMTU)
                        console.log('向蓝牙写数据===v2', data);
                        this.writeBluetoothData(data)
                    }
                } else {
                    this.writeBluetoothData(str)
                }

                this.$logs({
                    info: '向蓝牙设备写数据v1',
                    data: str
                })
			},
			//监听设备端回调的数据
			onBLECharacteristicValue() {
				// uni.showLoading({
				// 	title: '连接中...',
				// 	mask: true,
				// })
				uni.onBLECharacteristicValueChange(res => {
					console.log('监听蓝牙设备发过来的数据:', res)
					let resHex = ab2hex(res.value)
					console.log('回调value：', resHex);
					console.log(resHex.length);
                    this.createCheckCode('010014')
                    if (this.version == 'v2') {
                        if (resHex.substring(0, 4) == '0009' && resHex.substring(10, 12) == '01') {
                            this.maxMTU = parseInt(resHex.substring(12, 16), 16)
                            this.setBLEMTU(this.maxMTU, this.writeBlueData())
                            this.buffer = ''
                        } else {
                            if (resHex.startsWith('8b8b0203') && !this.buffer) {
                                this.buffer = resHex
                            }
                            if (this.buffer) {
                                this.buffer = this.buffer + resHex
                            }
                            console.log('this.buffer===',this.buffer,'mmmm==',this.buffer.lastIndexOf('8b8b0203'));
                            if (this.buffer.lastIndexOf('8b8b0203') > 0) {
                                let idx = this.buffer.lastIndexOf('8b8b0203')
                                this.parseBleConfigResult(this.buffer.slice(0, idx))
                                this.buffer = this.buffer.slice(idx)
                            }
                        }
                    } else {
                        if (resHex.length < 25) {
                            //回调成功
                            console.log(resHex.substring(18, 20));
                            console.log(resHex.substring(18, 20) == '00');
                            if (resHex.substring(18, 20) == '00') {
                                this.isReceived = true
                                if (this.time < 1) {
                                    this.isLinked = false
                                    this.linkshow = false
                                    this.cancellink()
                                    this.$logs({
                                        info: '配网失败',
                                        deviceId: this.device.deviceId,
                                        device: this.device,
                                    })
                                    uni.showToast({
                                        title: '配网失败',
                                        icon: 'none',
                                        duration: 1500,
                                    })
                                }
                            } else if (resHex.substring(18, 20) == '53') {
                                this.$logs({
                                    info: '设备连接路由器失败，路由器密码错误',
                                    deviceId: this.device.deviceId,
                                    device: this.device,
                                })
                                uni.showModal({
                                    title: '提示',
                                    content: '设备连接路由器失败，路由器密码错误，请输入正确密码后重新配网',
                                    confirmColor: '#FF0025',
                                    showCancel: false,
                                    success: (res) => {
                                        if (res.confirm) {
                                            // this.cancellink()
                                        }
                                    }
                                })
                            }
                        } else {
                            //配网成功
                            console.log(resHex.substring(18, 20) == '00');
                            if (resHex.substring(18, 20) == '00') {
                                clearInterval(this.timerId)
                                this.isDistributeNet = true;
                                // uni.showToast({
                                // 	title: '配网成功',
                                // 	icon: 'success',
                                // 	duration: 2000
                                // });
                                this.showToast('配网成功')
                                //解析结果
                                this.parseBleConfigResult(resHex.slice(18))
                            } else {
                                uni.showToast({
                                    title: buletoothCodeMsg[Number(resHex.substring(18, 20))],
                                    icon: 'none',
                                    duration: 2000
                                });
                            }
                        }
                    }
					// //解析结果
					// this.parseBleConfigResult(resHex.slice(18))
				})
			},
			//写入蓝牙的数据（16进制字符串）
			combineFlame() {
				let flameContent = ''
				let stringBuilder = '8B8B0101000200'
				let wifiName = this.WIFI.wifiName
				let wifiNameSize = stringToByte(wifiName).length
				let wifiPwd = this.WIFI.wifiPwd
				let wifiPwdSize = stringToByte(wifiPwd).length
				let pwdType = '0'
				let wifiNameSizeFill = useStrFill(wifiNameSize.toString(16), 2, '0', true)
				let wifiPwdSizeFill = useStrFill(wifiPwdSize.toString(16), 2, '0', true)
				let pwdTypeFill = useStrFill(pwdType.toString(16), 2, '0', true)
				// let wifiNameStr = strToHexCharCode(wifiName)
				let wifiNameStr = stringToUTF8Bytes(wifiName)
				let wifiPwdStr = strToHexCharCode(wifiPwd)
				flameContent = `${wifiNameSizeFill}${wifiNameStr}${wifiPwdSizeFill}${wifiPwdStr}${pwdTypeFill}`
				let flameContentFill = useStrFill(((flameContent.length) / 2).toString(16), 4, '0', true)
				stringBuilder = `${stringBuilder}${flameContentFill}${flameContent}`
				let checkCode = this.createCheckCode(stringBuilder)
				stringBuilder = `${stringBuilder}${checkCode}`
				// console.log('wifi===',wifiName,wifiNameStr,wifiNameSize,wifiNameSizeFill,wifiPwdSizeFill);
				// console.log('wifiPwd===',wifiPwd,wifiPwdStr,wifiPwdSize,wifiPwdSizeFill,pwdTypeFill);
				// console.log('1111===',flameContent,flameContent.length,flameContentFill,stringBuilder,checkCode);
				console.log('stringBuilder', stringBuilder.toUpperCase());

				return stringBuilder.toUpperCase()
			},
			// 解析蓝牙配网结果
			parseBleConfigResult(data) {
				console.log('hexData:', data);
                let hexData = ''
                if(this.version == 'v2'){
                    let checksum = data.slice(data.length - 2)
                    let content = data.slice(0, data.length - 2)
                    let cChecksum = this.createCheckCode(content)
                    hexData = data.slice(18)
                    console.log('解析蓝牙配网结果校验和:', checksum,cChecksum,data.substring(18,20));
                    if((checksum == cChecksum)&&data.substring(18,20)=='00'){
                        this.parseFinallyResult(hexData)
                        clearInterval(this.timerId)
                        this.isDistributeNet = true
                        uni.showToast({
                            title: '配网成功',
                            icon: 'success',
                            duration: 2000
                        });
                    }else if(data.substring(18,20)=='50'){
                        this.showErrTotast('配网失败-未知错误')
                    }else if(data.substring(18,20)=='53'){
                        this.showErrTotast('路由器密码错误')
                    }else if(data.substring(18,20)=='55'){
                        this.showErrTotast('配网失败-未知错误')
                    }
                }else{
                    hexData = data//data.substring(0, 2)
                    let connectResult = hexData.substring(0, 2)
                    if (connectResult == '00') {
                        this.parseFinallyResult(hexData)
                    } else if (connectResult == '53') {
                        //配网失败，路由器密码错误
                        this.showErrTotast('路由器密码错误')
                    } else {
                        //其他错误，设备端会一直重试
                    }
                }
                this.$logs({
                    info: '蓝牙配网结果',
                    data: hexData
                })
			},
            //解析最终结果
            parseFinallyResult(hexData){
                console.log('解析最终结果parseFinallyResult',hexData);
                let sLen = 0
                let eLen = 0
                //随机设备登录名长度
                let userNameLen = parseInt(hexData.substring(2, 4), 16)
                //随机设备登录名
                sLen = 4;
                eLen = userNameLen * 2 + 4;
                let userName = hexData.substring(sLen, eLen);
                let userNameByte = stringToByte(userName)
                //随机密码长度
                sLen = userNameLen * 2 + 4;
                eLen = userNameLen * 2 + 6;
                let passwordLen = parseInt(hexData.substring(sLen, eLen), 16);
                //随机密码
                sLen = userNameLen * 2 + 6;
                eLen = passwordLen * 2 + userNameLen * 2 + 6;
                let password = hexData.substring(sLen, eLen); /////////
                //设备序列号长度
                sLen = passwordLen * 2 + userNameLen * 2 + 6;
                eLen = passwordLen * 2 + userNameLen * 2 + 8;
                let devIdLen = parseInt(hexData.substring(sLen, eLen), 16);
                //设备序列号
                sLen = passwordLen * 2 + userNameLen * 2 + 8;
                eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 8;
                let devId = hexData.substring(sLen, eLen); ///////////////
                console.log('devid===', hexToString(devId));
                //设备IP地址
                sLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 8;
                eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 16;
                let devIp = hexData.substring(sLen, eLen);

                //设备MAC地址
                sLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 16;
                eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 28;
                let mac = hexData.substring(sLen, eLen);
                let tokenLen = 0;
                let token = null;
                if (hexData.length > eLen) {
                    //获取设备登录Token长度
                    sLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 28;
                    eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 30;
                    tokenLen = parseInt(hexData.substring(sLen, eLen), 16)

                    //获取设备登录Token
                    sLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 30;
                    eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 30 + tokenLen * 2;
                    token = hexData.substring(sLen, eLen);
                }
                console.log('userName:', userName, 'passwordLen:', passwordLen, 'password:', password, 'devIdLen:',
                    devIdLen, 'devId:', devId, 'devIp:', devIp, 'mac:', mac, 'tokenlenL=:', tokenLen, 'token:',
                    token);
                let data = {
                    deviceNo: hexToString(devId),
                    deviceType: this.device.deviceInfo.description,
                    pid: this.device.pid,
                    devicePic: this.device.deviceInfo.devicePic,
                    adminToken: token ? hexToString(token) : ''
                }
                uni.hideLoading()
                wx.reLaunch({
                    url: `/jvss/pagesDevice/device/bluetooth/equipment-rename?device=${encodeURIComponent(JSON.stringify(data))}&connecttype=bluetooth`
                })
                this.$logs({
                    info: '蓝牙配网成功',
                    data: hexData,
                    userName: userName,
                    passwordLen: passwordLen,
                    password: password,
                    devIdLen: devIdLen,
                    devId: devId,
                    devIp: devIp,
                    mac: mac,
                    tokenlenL: tokenLen,
                    token: token,
                    deviceNo: hexToString(devId),
                    deviceType: this.device.deviceInfo.description
                })
            },
			//校验和
			createCheckCode(str) {
				let total = 0
				for (var i = 0; i < str.length / 2; i++) {
					let currentI = i * 2
					let i12 = currentI + 2
					let subString = str.substring(currentI, i12)
					total += parseInt(subString, 16)
				}
				let result = useStrFill((total % 256).toString(16), 2, '0', true)
				console.log('校验和', result);
				return result
			},
			//取消配网
			cancellink() {
				this.linkshow = false
				if (this.timerId) {
					clearInterval(this.timerId)
				}
				this.time = 180;
				this.stopBluetoothDevicesDiscovery()
			},
			showToast(e) {
				this.jshowtoast = false;
				this.title = e
				this.jshowtoast = true;
				setTimeout(() => {
					this.jshowtoast = false;
				}, 2000)
			}
		}
	}
</script>

<style lang="scss">
	.qrcode {
		padding: 20upx 0 20upx 0;
		display: flex;
		justify-content: center;
		width: 98vw;
		margin: auto;
		align-items: center;

		.qrcanvas {
			// width: 300rpx;
			// height: 300rpx;
			// width: 90vw;
			// height: 90vw;
		}

		.qrimg {
			width: 90vw;
			height: 90vw;
		}

		.qrimg2 {
			width: 200px;
			height: 200px;
		}
	}

	.title {
		text-align: center;
		margin-top: 60rpx;

		.title-c {
			color: #FD974C;
			font-weight: bold;
			font-size: 40rpx;
		}

		.title-p {
			color: #666;
			font-weight: bold;
			font-size: 26rpx;
			margin-top: 20rpx;
		}
	}

	.popup-connect {
		z-index: 999;
		background-color: #fff;
		padding-bottom: 20rpx;
		border-radius: 10rpx;
		text-align: center;
	}

	.popup-header {
		position: relative;
		border-bottom: 1rpx solid #EEEEEE;
		padding: 20rpx;

		.p-title {
			font-size: 26rpx;
		}

		.close {
			position: absolute;
			right: 10rpx;
			top: 30rpx;
		}
	}

	.qrcode-hint {
		width: 80%;
		margin: auto;
		color: #666;
		font-size: 26rpx;
		margin-top: 20rpx;

		span {
			color: #FF0025;
		}
	}

	.popup-content {
		padding: 30rpx;
		overflow: scroll;
		text-align: left;

		text {
			margin-top: 20rpx;
			color: #AFAFAF;
			font-size: 24rpx;
		}
	}

	.popup-tips {
		border-top: 1rpx solid #EEEEEE;
		padding: 20rpx;
		color: #FF0025;
		font-size: 26rpx;
		text-align: center;
	}

	.popup-button button {
		width: 90% !important;
		height: 80rpx;
		border: none;
		font-size: 30rpx;

	}

	.popup-qrimg {
		background-color: #fff;
		width: 90vw;
		height: 600rpx;
		box-sizing: border-box;
		padding: 40rpx;
		border-radius: 15rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.qrimg {
			width: 260px;
			height: 260px;
		}

		.qrimg2 {
			width: 160px;
			height: 160px;
		}
	}

	.popup-device {
		width: 90vw;
		// height: 294rpx;
		padding-bottom: 30rpx;
		background: #FFFFFF;
		border-radius: 15rpx;
		opacity: 1;
		margin-top: 20rpx;

		.title-number {
			display: flex;
			justify-content: space-between;
			padding: 20rpx;
			padding: 20rpx 20rpx 20rpx 40rpx;
			font-weight: bold;
		}

		.device-list {

			display: flex;
			align-items: center;

			.deviceImg {
				width: 150rpx;
				height: 150rpx;
				margin-left: 20rpx;
				flex-shrink: 0;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.device-info {
				font-size: 28rpx;
				color: #2B2B2B;
				margin-left: 20rpx;
			}

			.text1 {
				font-size: 22rpx;
				color: #B8B8B8;
				margin: 10rpx 0;
			}
		}

		.device-lists {
			width: 100%;
			overflow-x: auto;
		}
	}
</style>
